function DSA_PlayerExists(playerid)
	result = sql.Query("SELECT unique_id FROM dsa_users WHERE unique_id='"..playerid.."' LIMIT 1")
	if(result) then
		return true
	else 
		return false
	end
end

function DSA_PlayerCreate(playerid, rank)
	if(DSA_PlayerExists(playerid)) then
		return false
	end
	sql.Query("INSERT INTO dsa_users (unique_id, rank) VALUES ('"..playerid.."', '"..rank.."')")
	if(DSA_PlayerExists(playerid)) then
		return true
	else
		return false
	end
end

function DSA_PlayerID(player)
	local DATA
	if(!SinglePlayer() && (GetConVarNumber("sv_lan") != 0)) then
		DATA = player:IPAddress()
	else
		DATA = player:SteamID()
	end
	return DATA
end

function DSA_GetPlayerRank(playerid)
	if(!DSA_PlayerExists(playerid)) then
		return false
	end
	local rank = sql.QueryValue("SELECT rank FROM dsa_users WHERE unique_id = '"..playerid.."' LIMIT 1")
	if(rank != nil) then
		return rank
	end
end

function DSA_GetRank(rank)
	local name = sql.QueryValue("SELECT name FROM dsa_ranks WHERE unique_id = '"..rank.."' LIMIT 1")
	local color = sql.QueryValue("SELECT color FROM dsa_ranks WHERE unique_id = '"..rank.."' LIMIT 1")
	local data = ""..name..","..color..""
	return data
end

function DSA_PlayerInitialSpawn(player)
	-- Tells the client, that DSA is installed.
	umsg.Start("DSA_Init", player)
	umsg.End()
	
	local ID = DSA_PlayerID(player)
	
	if(DSA_PlayerExists(ID)) then
		Msg(ID.." DOES EXISTS!\n")
	else
		Msg("[DSA] Create new user "..ID.."\n")
		DSA_PlayerCreate(ID, "0")
	end
	
	local RANK = DSA_GetPlayerRank(ID)
	local RANKEX = DSA_GetRank(RANK)
	
	umsg.Start("DSA_PLY_RANK", player)
		umsg.String(RANKEX)
	umsg.End()
	
	
	Msg(ID.." RANK IS: "..RANK.."\n")
end